package com.ssy.lingxi.order.serviceimpl.platform;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.basic.FundModeEnum;
import com.ssy.lingxi.common.constant.order.OrderPayChannelEnum;
import com.ssy.lingxi.common.constant.order.OrderPayTypeEnum;
import com.ssy.lingxi.common.constant.order.OrderPaymentParameterEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.order.entity.BaseOrderPayChannelDO;
import com.ssy.lingxi.order.entity.MemberParameterDO;
import com.ssy.lingxi.order.entity.MemberPaymentDO;
import com.ssy.lingxi.order.entity.PlatformPaymentParameterDO;
import com.ssy.lingxi.order.model.bo.PaymentParameterBO;
import com.ssy.lingxi.order.model.dto.MemberDTO;
import com.ssy.lingxi.order.model.dto.OrderMemberQueryDTO;
import com.ssy.lingxi.order.model.vo.basic.request.OrderPayChannelVO;
import com.ssy.lingxi.order.model.vo.payment.request.PaymentParameterChannelVO;
import com.ssy.lingxi.order.model.vo.payment.request.PaymentParameterInsertOrUpdateVO;
import com.ssy.lingxi.order.model.vo.payment.request.PaymentParameterVO;
import com.ssy.lingxi.order.model.vo.payment.response.PaymentParameterChannelDetailVO;
import com.ssy.lingxi.order.model.vo.payment.response.PaymentParameterDetailVO;
import com.ssy.lingxi.order.model.vo.payment.response.PaymentParameterItemVO;
import com.ssy.lingxi.order.model.vo.payment.response.PaymentParameterPayTypeDetailVO;
import com.ssy.lingxi.order.model.vo.platform.request.MemberPaymentIdVO;
import com.ssy.lingxi.order.model.vo.platform.request.MemberPaymentPageVO;
import com.ssy.lingxi.order.model.vo.platform.request.MemberPaymentStatusVO;
import com.ssy.lingxi.order.model.vo.platform.request.MemberPaymentVO;
import com.ssy.lingxi.order.model.vo.platform.response.MemberPaymentQueryVO;
import com.ssy.lingxi.order.repository.BaseOrderPayChannelRepository;
import com.ssy.lingxi.order.repository.MemberParameterRepository;
import com.ssy.lingxi.order.repository.MemberPaymentRepository;
import com.ssy.lingxi.order.repository.PlatformPaymentParameterRepository;
import com.ssy.lingxi.order.service.base.IBaseCacheService;
import com.ssy.lingxi.order.service.feign.IMemberFeignService;
import com.ssy.lingxi.order.service.feign.IPayFeignService;
import com.ssy.lingxi.order.service.platform.IPlatformPaymentParameterService;
import com.ssy.lingxi.order.service.web.IMemberPaymentParameterService;
import com.ssy.lingxi.order.utils.NumberUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 平台支付参数设置相关接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-08-12
 */
@Service
public class PlatformPaymentParameterServiceImpl implements IPlatformPaymentParameterService {
    @Resource
    private IBaseCacheService baseCacheService;

    @Resource
    private IMemberPaymentParameterService memberPaymentParameterService;

    @Resource
    private IMemberFeignService memberFeignService;

    @Resource
    private IPayFeignService payFeignService;

    @Resource
    private BaseOrderPayChannelRepository baseOrderPayChannelRepository;

    @Resource
    private PlatformPaymentParameterRepository platformPaymentParameterRepository;

    @Resource
    private MemberParameterRepository memberParameterRepository;

    @Resource
    private MemberPaymentRepository memberPaymentRepository;

    /**
     * 查询支付参数配置详情
     *
     * @param headers HttpHeaders信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<PaymentParameterPayTypeDetailVO>> findParameters(HttpHeaders headers) {
        baseCacheService.needLoginFromManagePlatform(headers);

        //Step 1: 从支付方式配置中查
        List<BaseOrderPayChannelDO> baseOrderPayChannels = baseOrderPayChannelRepository.findByPayTypeInAndStatus(Stream.of(OrderPayTypeEnum.CASH_ON_DELIVERY.getCode(),  OrderPayTypeEnum.COMMERCE_IMPORT_PAY.getCode(), OrderPayTypeEnum.ONLINE_PAYMENT.getCode(), OrderPayTypeEnum.OFFLINE_PAYMENT.getCode(), OrderPayTypeEnum.ALLIN_PAY.getCode(), OrderPayTypeEnum.CCB_PAY.getCode()).collect(Collectors.toList()), EnableDisableStatus.ENABLE.getCode());
        if(CollectionUtils.isEmpty(baseOrderPayChannels)) {
            return Wrapper.success();
        }

        //Step 2:查询已有的配置
        List<PlatformPaymentParameterDO> platformPaymentParameters = platformPaymentParameterRepository.findAll();

        //Step 3:拼接查询结果
        return Wrapper.success(baseOrderPayChannels.stream().collect(Collectors.groupingBy(BaseOrderPayChannelDO::getPayType)).entrySet().stream().map(entry -> {
            PaymentParameterPayTypeDetailVO detailVO = new PaymentParameterPayTypeDetailVO();
            detailVO.setPayType(entry.getKey());
            detailVO.setPayTypeName(OrderPayTypeEnum.getNameByCode(entry.getKey()));

            //已有的配置
            List<PlatformPaymentParameterDO> paymentParameters = platformPaymentParameters.stream().filter(paymentParameter -> paymentParameter.getPayType().equals(entry.getKey())).collect(Collectors.toList());

            detailVO.setChannels(entry.getValue().stream().map(baseOrderPayChannel -> {
                PaymentParameterChannelDetailVO channelDetailVO = new PaymentParameterChannelDetailVO();
                channelDetailVO.setPayChannel(baseOrderPayChannel.getPayChannel());
                channelDetailVO.setPayChannelName(baseOrderPayChannel.getPayChannelName());
                //从已有的配置中查询参数
                PlatformPaymentParameterDO parameter = paymentParameters.stream().filter(paymentParameter -> paymentParameter.getPayChannel().equals(baseOrderPayChannel.getPayChannel())).findFirst().orElse(null);
                channelDetailVO.setParameters(parameter == null || CollectionUtils.isEmpty(parameter.getParameters()) ? new ArrayList<>() : parameter.getParameters().stream().map(p -> {
                    PaymentParameterDetailVO parameterDetailVO = new PaymentParameterDetailVO();
                    parameterDetailVO.setCode(p.getCode());
                    parameterDetailVO.setKey(OrderPaymentParameterEnum.getKeyByCode(p.getCode()));
                    parameterDetailVO.setValue(p.getValue());
                    parameterDetailVO.setRemark(p.getRemark());
                    return parameterDetailVO;
                }).collect(Collectors.toList()));
                return channelDetailVO;
            }).collect(Collectors.toList()));

            //勾选的配置
            detailVO.setPayChannels(paymentParameters.stream().map(PlatformPaymentParameterDO::getPayChannel).collect(Collectors.toList()));
            return detailVO;
        }).collect(Collectors.toList()));
    }

    /**
     * 根据支付渠道，查询支付参数下拉框列表
     *
     * @param headers    HttpHeaders信息
     * @param channelVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<PaymentParameterItemVO>> findPayChannelParameters(HttpHeaders headers, OrderPayChannelVO channelVO) {
        baseCacheService.needLoginFromManagePlatform(headers);
        //不显示支付宝第三方授权 app_auth_token
        return Wrapper.success(Arrays.stream(OrderPaymentParameterEnum.values()).filter(e -> e.getPayChannels().stream().anyMatch(c -> c.getCode().equals(channelVO.getPayChannel())) && !e.getCode().equals(OrderPaymentParameterEnum.ALIPAY_THREAD_APP_AUTH_TOKEN.getCode())).sorted(Comparator.comparingInt(OrderPaymentParameterEnum::getCode)).map(e -> {
            PaymentParameterItemVO parameterVO = new PaymentParameterItemVO();
            parameterVO.setCode(e.getCode());
            parameterVO.setKey(e.getKey());
            return parameterVO;
        }).collect(Collectors.toList()));
    }

    /**
     * 新增或修改平台支付参数设置
     *
     * @param headers    HttpHeaders信息
     * @param parameterVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> createParameters(HttpHeaders headers, PaymentParameterInsertOrUpdateVO parameterVO) {
        UserLoginCacheDTO loginUser = baseCacheService.needLoginFromManagePlatform(headers);

        if(CollectionUtils.isEmpty(parameterVO.getParameters())) {
            return Wrapper.success();
        }

        //Step 1: 校验参数配置
        Wrapper<Void> checkResult = checkPaymentParameters(parameterVO);
        if(checkResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(checkResult.getCode(), checkResult.getMessage());
        }

        //Step 2: 删除已有的
        platformPaymentParameterRepository.deleteAll();

        //Step 3: 筛选非空的渠道参数配置，新增
        List<PlatformPaymentParameterDO> paymentParameters = parameterVO.getParameters().stream().flatMap(parameter -> parameter.getChannels().stream().map(channel -> {
            PlatformPaymentParameterDO paymentParameter = new PlatformPaymentParameterDO();
            paymentParameter.setMemberId(loginUser.getMemberId());
            paymentParameter.setRoleId(loginUser.getMemberRoleId());
            paymentParameter.setPayType(parameter.getPayType());
            paymentParameter.setPayTypeName(OrderPayTypeEnum.getNameByCode(parameter.getPayType()));
            paymentParameter.setPayChannel(channel.getPayChannel());
            paymentParameter.setPayChannelName(OrderPayChannelEnum.getNameByCode(channel.getPayChannel()));
            paymentParameter.setParameters(CollectionUtils.isEmpty(channel.getParameters()) ? new ArrayList<>() : channel.getParameters().stream().map(p -> {
                PaymentParameterBO parameterBO = new PaymentParameterBO();
                parameterBO.setCode(p.getCode());
                parameterBO.setValue(p.getValue());
                parameterBO.setRemark(StringUtils.hasLength(p.getRemark()) ? p.getRemark().trim() : "");
                return parameterBO;
            }).collect(Collectors.toList()));
            return paymentParameter;
        })).collect(Collectors.toList());

        platformPaymentParameterRepository.saveAll(paymentParameters);

        //调用支付服务接口，缓存通联支付参数
        payFeignService.cacheAllInPayParameters(paymentParameters.stream().filter(payment -> payment.getPayType().equals(OrderPayTypeEnum.ALLIN_PAY.getCode())).flatMap(payment -> payment.getParameters().stream()).collect(Collectors.toList()));
        //删除建行支付缓存
        payFeignService.removeCcbPayParameters();
        return Wrapper.success();
    }

    /**
     * 校验支付参数配置
     * @param parameterVO 接口参数
     * @return 校验结果
     */
    private Wrapper<Void> checkPaymentParameters(PaymentParameterInsertOrUpdateVO parameterVO) {
        if(parameterVO == null || CollectionUtils.isEmpty(parameterVO.getParameters())) {
            return Wrapper.success();
        }

        List<PaymentParameterChannelVO> parameterChannels = parameterVO.getParameters().stream().filter(p -> !CollectionUtils.isEmpty(p.getChannels())).flatMap(p -> p.getChannels().stream()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(parameterChannels)) {
            return Wrapper.success();
        }

        List<PaymentParameterVO> paymentParameters = parameterChannels.stream().filter(parameterChannel -> !CollectionUtils.isEmpty(parameterChannel.getParameters())).flatMap(parameterChannel -> parameterChannel.getParameters().stream()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(paymentParameters)) {
            return Wrapper.success();
        }

        //参数校验
        for (PaymentParameterVO paymentParameter : paymentParameters) {
            //建行B2B支付、数字人民币支付的超时时间（小时）要大于0
            if(paymentParameter.getCode().equals(OrderPaymentParameterEnum.CCB_B2B_TIME_OUT_HOURS.getCode()) || paymentParameter.getCode().equals(OrderPaymentParameterEnum.CCB_DIGITAL_TIME_OUT_HOURS.getCode())) {
                if(StringUtils.hasLength(paymentParameter.getValue()) && NumberUtil.notLongOrNegativeZero(paymentParameter.getValue())) {
                    return Wrapper.fail(ResponseCode.ORDER_PAYMENT_PARAMETER_CBC_TIMEOUT_MUST_GT_ZERO);
                }
            }
        }

        return Wrapper.success();
    }

    /**
     * “商户参数配置” - 查询支付参数配置详情
     *
     * @param headers HttpHeaders信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<PaymentParameterDetailVO>> findMemberCommonParameters(HttpHeaders headers, OrderPayChannelVO channelVO) {
        baseCacheService.needLoginFromManagePlatform(headers);
        MemberParameterDO parameter = memberParameterRepository.findFirstByPayChannel(channelVO.getPayChannel());
        if(parameter == null) {
            return Wrapper.success(new ArrayList<>());
        }

        return Wrapper.success(parameter.getParameters().stream().map(p -> {
            PaymentParameterDetailVO detail = new PaymentParameterDetailVO();
            detail.setCode(p.getCode());
            detail.setKey(OrderPaymentParameterEnum.getKeyByCode(p.getCode()));
            detail.setValue(p.getValue());
            detail.setRemark(p.getRemark());
            return detail;
        }).sorted(Comparator.comparingInt(PaymentParameterDetailVO::getCode)).collect(Collectors.toList()));
    }

    /**
     * “商户参数配置” - 根据支付渠道，查询支付参数下拉框列表
     *
     * @param headers   HttpHeaders信息
     * @param channelVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<PaymentParameterItemVO>> findMemberCommonPayChannelParameters(HttpHeaders headers, OrderPayChannelVO channelVO) {
        //目前只有“在线支付” - “支付宝” 才能配置会员通用参数
        if(channelVO.getPayChannel().equals(OrderPayChannelEnum.ALIPAY.getCode())) {
            return Wrapper.success(Stream.of(OrderPaymentParameterEnum.ALIPAY_APP_ID, OrderPaymentParameterEnum.ALIPAY_PUBLIC_KEY, OrderPaymentParameterEnum.APP_ALIPAY_PRIVATE_KEY).map(p -> new PaymentParameterItemVO(p.getCode(), p.getKey())).sorted(Comparator.comparingInt(PaymentParameterItemVO::getCode)).collect(Collectors.toList()));
        }

        return Wrapper.success(new ArrayList<>());
    }

    /**
     * “商户参数配置” - 新增或修改商户参数设置
     *
     * @param headers     HttpHeaders信息
     * @param parameterVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> createMemberCommonParameters(HttpHeaders headers, PaymentParameterChannelVO parameterVO) {
        baseCacheService.needLoginFromManagePlatform(headers);

        //Step 1: 新增或修改
        MemberParameterDO parameter = memberParameterRepository.findFirstByPayChannel(parameterVO.getPayChannel());
        if(parameter == null) {
            OrderPayTypeEnum payType = Arrays.stream(OrderPayTypeEnum.values()).filter(p -> p.getPayChannels().stream().anyMatch(payChannel -> payChannel.getCode().equals(parameterVO.getPayChannel()))).findFirst().orElse(null);
            if(payType == null) {
                return Wrapper.fail(ResponseCode.ORDER_PAY_TYPE_DOES_NOT_EXIST);
            }

            parameter = new MemberParameterDO();
            parameter.setPayType(payType.getCode());
            parameter.setPayChannel(parameterVO.getPayChannel());
        }

        parameter.setParameters(CollectionUtils.isEmpty(parameterVO.getParameters()) ? new ArrayList<>() : parameterVO.getParameters().stream().map(p -> new PaymentParameterBO(p.getCode(), p.getValue(), p.getRemark())).collect(Collectors.toList()));
        memberParameterRepository.saveAndFlush(parameter);

        //Step 2: 修改会员参数配置
        return memberPaymentParameterService.insertOrUpdateMemberPaymentParameter(parameter.getPayType(), parameter.getPayChannel(), parameter.getParameters());
    }

    /**
     * 分页查询商户支付参数配置列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberPaymentQueryVO>> pageMemberPayments(HttpHeaders headers, MemberPaymentPageVO pageVO) {
        baseCacheService.needLoginFromManagePlatform(headers);
        return StringUtils.hasText(pageVO.getName()) ? pageMemberPayments(pageVO.getName(), pageVO.getCurrent(), pageVO.getPageSize()) : pageMemberPayments(pageVO.getCurrent(), pageVO.getPageSize());
    }

    /**
     * 分页查询商户支付参数配置列表（先从会员服务根据名称查询，再拼接查询结果）
     * @param name  会员名称
     * @param current 当前页
     * @param pageSize 每页行数
     * @return 查询结果
     */
    private Wrapper<PageData<MemberPaymentQueryVO>> pageMemberPayments(String name, int current, int pageSize) {
        //Step 1: 从会员服务查询会员类型为企业、企业个人，角色类型为服务提供者的平台会员列表
        Wrapper<List<OrderMemberQueryDTO>> memberResult = memberFeignService.listPlatformMembers(name, new ArrayList<>());
        if(memberResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(memberResult.getCode(), memberResult.getMessage());
        }

        if(CollectionUtils.isEmpty(memberResult.getData())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //Step 2: 构造本地查询条件，注意是or查询
        Specification<MemberPaymentDO> specification = (Specification<MemberPaymentDO>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = memberResult.getData().stream().map(member -> criteriaBuilder.and(criteriaBuilder.equal(root.get("memberId").as(Long.class), member.getMemberId()), criteriaBuilder.equal(root.get("roleId").as(Long.class), member.getRoleId()))).collect(Collectors.toList());
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.or(list.toArray(p));
        };

        //Step 3: 分页查询，拼接会员信息并返回
        Pageable pageable = PageRequest.of(current - 1,  pageSize, Sort.by("id").descending());
        Page<MemberPaymentDO> pageList = memberPaymentRepository.findAll(specification, pageable);
        return makeMemberPaymentQueryResult(pageList, CollectionUtils.isEmpty(memberResult.getData()) ? new ArrayList<>() : memberResult.getData());
    }

    /**
     * 分页查询商户支付参数配置列表（先查询商户支付参数配置，再拼接从会员服务查询的结果）
     * @param current 当前页
     * @param pageSize 每页行数
     * @return 查询结果
     */
    private Wrapper<PageData<MemberPaymentQueryVO>> pageMemberPayments(int current, int pageSize) {
        //Step 1: 先分页查询商户支付参数配置
        Pageable pageable = PageRequest.of(current - 1,  pageSize, Sort.by("id").descending());
        Page<MemberPaymentDO> pageList = memberPaymentRepository.findAll(pageable);

        //不能根据totalCount判断，要根据查询结果是否为空判断
        if(CollectionUtils.isEmpty(pageList.getContent())) {
            return Wrapper.success(new PageData<>(pageList.getTotalElements(), new ArrayList<>()));
        }

        //Step 2:从会员服务查询会员信息
        Wrapper<List<OrderMemberQueryDTO>> memberResult = memberFeignService.listPlatformMembers("", pageList.getContent().stream().map(payment -> new MemberDTO(payment.getMemberId(), payment.getRoleId())).collect(Collectors.toList()));
        if(memberResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(memberResult.getCode(), memberResult.getMessage());
        }

        //Step 3: 拼接会员信息并返回
        return makeMemberPaymentQueryResult(pageList, CollectionUtils.isEmpty(memberResult.getData()) ? new ArrayList<>() : memberResult.getData());
    }

    /**
     * 拼接商户支付策略分页查询结果
     * @param pageList 分页查询商户支付策略的结果
     * @param members  从会员服务查询返回的会员信息
     * @return 查询结果
     */
    private Wrapper<PageData<MemberPaymentQueryVO>> makeMemberPaymentQueryResult(Page<MemberPaymentDO> pageList, List<OrderMemberQueryDTO> members) {
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(payment -> {
            MemberPaymentQueryVO queryVO = new MemberPaymentQueryVO();
            queryVO.setPaymentId(payment.getId());
            queryVO.setMemberId(payment.getMemberId());
            queryVO.setRoleId(payment.getRoleId());
            queryVO.setFundMode(payment.getFundMode());
            queryVO.setFundModeName(FundModeEnum.getNameByCode(payment.getFundMode()));
            queryVO.setPayType(payment.getPayType());
            queryVO.setPayTypeName(OrderPayTypeEnum.getNameByCode(payment.getPayType()));
            queryVO.setPayChannel(payment.getPayChannel());
            queryVO.setPayChannelName(OrderPayChannelEnum.getNameByCode(payment.getPayChannel()));
            queryVO.setCode(payment.getCode());
            queryVO.setValue(payment.getValue());
            queryVO.setRemark(payment.getRemark());
            queryVO.setStatus(payment.getStatus());
            queryVO.setStatusName(EnableDisableStatus.getNameByCode(payment.getStatus()));
            members.stream().filter(member -> member.getMemberId().equals(payment.getMemberId()) && member.getRoleId().equals(payment.getRoleId())).findFirst().ifPresent(member -> {
                queryVO.setName(member.getName());
                queryVO.setRoleName(member.getRoleName());
                queryVO.setMemberTypeName(member.getMemberTypeName());
                queryVO.setLevelTag(member.getLevelTag());
            });

            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 新增商户支付参数配置时，查询支付参数下拉框列表
     *
     * @param headers HttpHeaders信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<PaymentParameterItemVO>> findMemberPaymentParameters(HttpHeaders headers) {
        PaymentParameterItemVO itemVO = new PaymentParameterItemVO();
        itemVO.setCode(OrderPaymentParameterEnum.ALIPAY_THREAD_APP_AUTH_TOKEN.getCode());
        itemVO.setKey(OrderPaymentParameterEnum.ALIPAY_THREAD_APP_AUTH_TOKEN.getKey());
        return Wrapper.success(Collections.singletonList(itemVO));
    }

    /**
     * 新增或修改商户支付参数配置
     *
     * @param headers   HttpHeaders信息
     * @param paymentVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> createMemberPayment(HttpHeaders headers, MemberPaymentVO paymentVO) {
        baseCacheService.needLoginFromManagePlatform(headers);
        //Step 1: 在商户支付参数配置表中保存数据
        MemberPaymentDO memberPayment = memberPaymentRepository.findFirstByMemberIdAndRoleId(paymentVO.getMemberId(), paymentVO.getRoleId());
        if(memberPayment == null) {
            memberPayment = new MemberPaymentDO();
            memberPayment.setMemberId(paymentVO.getMemberId());
            memberPayment.setRoleId(paymentVO.getRoleId());
            memberPayment.setFundMode(FundModeEnum.DIRECT_TO_ACCOUNT.getCode());
            memberPayment.setPayType(OrderPayTypeEnum.ONLINE_PAYMENT.getCode());
            memberPayment.setPayChannel(OrderPayChannelEnum.ALIPAY.getCode());
            memberPayment.setCode(OrderPaymentParameterEnum.ALIPAY_THREAD_APP_AUTH_TOKEN.getCode());
            memberPayment.setStatus(EnableDisableStatus.ENABLE.getCode());
        }

        memberPayment.setValue(paymentVO.getValue());
        memberPayment.setRemark(StringUtils.hasLength(paymentVO.getRemark()) ? paymentVO.getRemark() : "");
        memberPaymentRepository.saveAndFlush(memberPayment);

        //Step 2: 新增或修改会员支付参数表中的配置
        return memberPaymentParameterService.insertOrUpdateMemberPaymentParameter(memberPayment);
    }

    /**
     * 修改商户支付参数配置状态
     *
     * @param headers  HttpHeaders信息
     * @param statusVO 接口参数
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> updateMemberPaymentStatus(HttpHeaders headers, MemberPaymentStatusVO statusVO) {
        MemberPaymentDO memberPayment = memberPaymentRepository.findById(statusVO.getPaymentId()).orElse(null);
        if(memberPayment == null) {
            return Wrapper.success();
        }

        memberPayment.setStatus(statusVO.getStatus());
        memberPaymentRepository.saveAndFlush(memberPayment);

        //新增/修改，或移除会员支付参数表中的配置
        return statusVO.getStatus().equals(EnableDisableStatus.ENABLE.getCode()) ? memberPaymentParameterService.insertOrUpdateMemberPaymentParameter(memberPayment) : memberPaymentParameterService.removeMemberPaymentParameter(memberPayment);
    }

    /**
     * 删除商户支付参数配置
     *
     * @param headers HttpHeaders信息
     * @param idVO    接口参数
     * @return 删除结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> deleteMemberPayment(HttpHeaders headers, MemberPaymentIdVO idVO) {
        MemberPaymentDO memberPayment = memberPaymentRepository.findById(idVO.getPaymentId()).orElse(null);
        if(memberPayment == null) {
            return Wrapper.success();
        }

        //移除会员支付参数表中的配置
        Wrapper<Void> parameterResult = memberPaymentParameterService.removeMemberPaymentParameter(memberPayment);
        if(parameterResult.getCode() != ResponseCode.SUCCESS.getCode()) {
            return Wrapper.fail(parameterResult);
        }

        //删除
        memberPaymentRepository.delete(memberPayment);
        return Wrapper.success();
    }
}
